package xyz.xpman.prisonerfitness.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import static java.lang.Thread.sleep;

public class TestService extends Service {
    /**
     * 行为
     */
    private static final String TAG = "TestService";
    public static final String ACTION = "xyz.xpman.prisonerfitness.service.TestService";

    private boolean running = false;

    private String data = "Default Message";

    public class Binder extends android.os.Binder {

        public void setData(String data) {
            TestService.this.data = data;
        }

        public TestService getService(){
            return TestService.this;
        }
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    public interface CallBack{
        void onDataChange(String data);
    }

    private CallBack callback = null;

    public void setCallback(CallBack callback) {
        this.callback = callback;
    }

    public CallBack getCallback() {
        return callback;
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "----- onCreate() ---");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "----- onStartCommand() ---");
        final String data = intent.getStringExtra("data");
        final String data2 = intent.getStringExtra("data2");
        Log.i(TAG, "----- onStartCommand() -> data: " + data + " | " + data2 + " ---");

        running = true;
        new Thread(() -> {
            

            // 任务逻辑
            int i = 0;

            while(running) {
                final String newData = i++ + ": " + data;

                if(callback != null){
                    callback.onDataChange(newData);
                }

                try {
                    sleep(1000);
                } catch (InterruptedException ignored) { }
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "----- onBind() ---");
        return new Binder();
    }


    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "----- onRebind() ---");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "----- onUnbind() ---");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "----- onDestroy() ---");
        running = false;
        super.onDestroy();
    }

}